package org.batatasframework.support.format;

import java.util.Arrays;
import java.util.List;

import org.batatasframework.common.NumberLimit;
import org.batatasframework.support.type.OptionalIterable;

import cn.bonoon.kernel.util.StringHelper;

/**
 * 结果是boolean值的进行格式化，支持的数据库类型包括
 * <p><ul>
 * <li>boolean类型
 * <li>数值类型
 * </ul></p>
 * 
 * 格式化的结果只有两个值，这两个值的显示的内容可以由调用者自定义，默认值为：
 * <p><ul>
 * <li>true  = {@value #DEFAULT_TRUE_VALUE}
 * <li>false = {@value #DEFAULT_FALSE_VALUE}
 * </ul></p>
 * @author jackson
 *
 */
public class BooleanFormat implements OptionalIterable, NumberLimit{
	/** true默认值 */
	public final static String DEFAULT_TRUE_VALUE = "是";
	/** false默认值 */
	public final static String DEFAULT_FALSE_VALUE = "否";
	/** 默认的格式化对象 */
	public final static BooleanFormat DEFAULT = new BooleanFormat(DEFAULT_TRUE_VALUE, DEFAULT_FALSE_VALUE);
	
	private final String trueValue;
	private final String falseValue;
	
	public BooleanFormat(String format){
		if(StringHelper.isEmpty(format)){
			this.trueValue = DEFAULT_TRUE_VALUE;
			this.falseValue = DEFAULT_FALSE_VALUE;
		}else{
			String[] args = format.split(" ");
			if(args.length > 0){
				this.trueValue = args[0];
				if(args.length > 1){
					this.falseValue = args[1];
				}else{
					this.falseValue = DEFAULT_FALSE_VALUE;
				}
			}else{
				this.trueValue = DEFAULT_TRUE_VALUE;
				this.falseValue = DEFAULT_FALSE_VALUE;
			}
		}
	}
	
	public BooleanFormat(String trueValue, String falseValue) {
		this.trueValue = trueValue;
		this.falseValue = falseValue;
	}
	
	/** boolean类型 */
	public String format(boolean value){
		return value ? trueValue : falseValue;
	}
	
	/** boolean对象类型 */
	public String format(Boolean value){
		return format(null != value && value.booleanValue());
	}
	
	/** 对数值类型的支持 */
	public String format(Number value){
		return format(null != value && value.intValue() == 1);
	}

	public String getTrueValue() {
		return trueValue;
	}

	public String getFalseValue() {
		return falseValue;
	}

	@Override
	public List<? extends OptionalEntry> getSources() {
		return Arrays.asList(
				new BooleanOptionalEntry(0, falseValue), 
				new BooleanOptionalEntry(1, trueValue));
	}
	
	private class BooleanOptionalEntry implements OptionalEntry{
		private final int value;
		private final String name;
		
		public BooleanOptionalEntry(int value, String name){
			this.value = value;
			this.name = name;
		}
		
		@Override
		public String getName() {
			return name;
		}
		
		@Override
		public Object getValue() {
			return value;
		}
		
	}

	@Override
	public long minValue() {
		return 0;
	}

	@Override
	public long maxValue() {
		return 1;
	}
}
